package com.itfreer.power.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.power.entity.user.VUserInfoEntity;
import com.itfreer.power.service.power.PowerService;
import com.itfreer.utils.sys.SystemParameter;

@Component
@Path("/currentuser/")
public class CurrentUserService {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private final static String s_user = "s_user";

	@Autowired(required = false)
	private PowerService powerService;

	@Autowired(required = false)
	private SystemParameter systemParameter;

	/**
	 * 设置用户密码
	 * 
	 * @param userid
	 *            唯一值
	 * @return
	 */
	@POST
	@Path("/setPassword/{op:.+}/{np:.+}")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public boolean setPassword(@Context HttpServletRequest request, @PathParam("op") String oldPwd,
			@PathParam("np") String newPwd) {
		if (powerService == null) {
			return false;
		}
		if (request == null) {
			return false;
		}
		final HttpSession httpSession = request.getSession(false);
		VUserInfoEntity userEntity = httpSession != null ? (VUserInfoEntity) httpSession.getAttribute(s_user) : null;
		if (userEntity == null) {
			return false;
		}
		return powerService.setPassword(userEntity.getUserid(), oldPwd, newPwd);
	}

	@POST
	@Path("/getUserInfo")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public Map<String, Object> getUserInfo(@Context HttpServletRequest request) {
		if (request == null) {
			logger.debug("获取当前用户失败，request为null。");
			return null;
		}

		final HttpSession httpSession = request.getSession(false);
		if (httpSession == null) {
			logger.debug("获取当前用户失败，httpSession为null。");
		}

		// 用户信息
		VUserInfoEntity userEntity = httpSession != null ? (VUserInfoEntity) httpSession.getAttribute(s_user) : null;
		if (userEntity == null) {
			logger.debug("获取当前用户失败，userEntity为null。");
		} else {
			logger.debug("获取当前用户成功，用户名为：" + userEntity.getUserName());
		}
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("user", userEntity);

		if (userEntity != null) {
			// 获取当前用户的角色列表
			if (userEntity.getRoleList() == null) {
				userEntity.setRoleList(powerService.getUserRoles(userEntity.getUserid()));
			}

			// 可访问的服务
			List<String> userService = null;
			if (userEntity.getIsSuperAdmin() != null && userEntity.getIsSuperAdmin()) {
				userService = new ArrayList<String>();
				userService.add("sa");
			} else {
				userService = powerService.getRoleService(userEntity.getRoleList());
			}
			result.put("services", userService);

			// 可访问的菜单标识
			String serviceId = "";
			if (systemParameter != null) {
				serviceId = systemParameter.getsId();
			}
			List<String> userMenus = null;
			if (userEntity.getIsSuperAdmin() != null && userEntity.getIsSuperAdmin()) {
				userMenus = new ArrayList<String>();
				userMenus.add("sa");
			} else {
				userMenus = powerService.getRoleMenus(userEntity.getRoleList(), serviceId);
			}
			result.put("menus", userMenus);
		} else {
			result.put("services", null);
			result.put("menus", null);
		}
		return result;
	}
	
	/**
	 * 是否登录系统
	 * 
	 * @param entity 添加实体
	 * @return
	 * @throws IOException
	 */
	@POST
	@Path("/isLogin")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public boolean isLogin(@Context HttpServletRequest request) throws IOException {
		if (request == null) {
			logger.debug("获取当前用户失败，request为null。");
			return false;
		}
		final HttpSession httpSession = request.getSession(false);
		if (httpSession == null) {
			logger.debug("获取当前用户失败，httpSession为null。");
		}
		VUserInfoEntity userEntity = httpSession != null ? (VUserInfoEntity) httpSession.getAttribute(s_user) : null;
		if (userEntity == null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 获取当前用户
	 * 
	 * @param entity
	 *            添加实体
	 * @return
	 * @throws IOException
	 */
	@POST
	@Path("/getCurrentUser")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public VUserInfoEntity getCurrentUser(@Context HttpServletRequest request) throws IOException {
		if (request == null) {
			logger.debug("获取当前用户失败，request为null。");
			return null;
		}
		final HttpSession httpSession = request.getSession(false);
		if (httpSession == null) {
			logger.debug("获取当前用户失败，httpSession为null。");
		}
		VUserInfoEntity userEntity = httpSession != null ? (VUserInfoEntity) httpSession.getAttribute(s_user) : null;
		if (userEntity == null) {
			logger.debug("获取当前用户失败，userEntity为null。");
		} else {
			logger.debug("获取当前用户成功，用户名为：" + userEntity.getUserName());
		}
		return userEntity;
	}

	/**
	 * 获取用户可访问的应用ID集
	 * 
	 * @param userid
	 *            唯一值
	 * @return
	 */
	@POST
	@Path("/getUserService")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public List<String> getUserService(@Context HttpServletRequest request) {
		if (powerService == null) {
			return null;
		}
		if (request == null) {
			return null;
		}

		final HttpSession httpSession = request.getSession(false);
		VUserInfoEntity userEntity = httpSession != null ? (VUserInfoEntity) httpSession.getAttribute(s_user) : null;
		if (userEntity == null) {
			return null;
		}
		if (userEntity.getIsSuperAdmin() != null && userEntity.getIsSuperAdmin()) {
			List<String> result = new ArrayList<String>();
			result.add("sa");
			return result;
		} else {
			return powerService.getUserService(userEntity.getUserid());
		}
	}

	/**
	 * 获取用户可访问菜单ID集
	 * 
	 * @param userid
	 *            唯一值
	 * @param serviceId
	 * @return
	 */
	@POST
	@Path("/getUserMenus")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public List<String> getUserMenus(@Context HttpServletRequest request) {
		if (powerService == null) {
			return null;
		}
		String serviceId = "";
		if (systemParameter != null) {
			serviceId = systemParameter.getsId();
		}
		if (request == null) {
			return null;
		}

		final HttpSession httpSession = request.getSession(false);
		VUserInfoEntity userEntity = httpSession != null ? (VUserInfoEntity) httpSession.getAttribute(s_user) : null;
		if (userEntity == null) {
			return null;
		}
		if (userEntity.getIsSuperAdmin() != null && userEntity.getIsSuperAdmin()) {
			List<String> result = new ArrayList<String>();
			result.add("sa");
			return result;
		} else {
			return powerService.getUserMenus(userEntity.getUserid(), serviceId);
		}
	}
}